package com.magold.event;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants;

public class ApplyVelocityResult extends TargetResult<EventDrivable> {
	private float mVelocityX;
	private float mVelocityY;
	private float mAngularVelocity;

	private boolean mEnableLinearVelocity, mEnableAngularVelocity;

	/**
	 * disable angular velocity set.
	 * @param vx in pixel
	 * @param vy in pixel
	 * @param pTarget
	 */
	public ApplyVelocityResult(float vx, float vy, EventDrivable pTarget) {
		super(pTarget);
		assignValue(vx, vy, 0);
		
		mEnableLinearVelocity = true;
		mEnableAngularVelocity = false;
	}

	/**
	 * disable linear velocity set.
	 * @param pAngularVelocity
	 * @param pTarget
	 */
	public ApplyVelocityResult(float pAngularVelocity, EventDrivable pTarget) {
		super(pTarget);
		assignValue(0, 0, pAngularVelocity);
		
		mEnableAngularVelocity = true;
		mEnableLinearVelocity = false;
	}
	
	/**
	 * set linear velocity and angular velocity both.
	 * @param vx
	 * @param vy
	 * @param pAngularVelocity
	 * @param pTarget
	 */
	public ApplyVelocityResult(float vx, float vy, float pAngularVelocity, EventDrivable pTarget) {
		super(pTarget);
		assignValue(vx, vy, pAngularVelocity);
		
		mEnableAngularVelocity = true;
		mEnableLinearVelocity = true;
	}
	
	private void assignValue(float vx, float vy, float pAngularVelocity) {
		mVelocityX = vx / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
		mVelocityY = vy / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
		mAngularVelocity = pAngularVelocity;
	}

	@Override
	public IUpdateHandler onConditionMatched(int pTimes) {
		if (pTimes != 1 || mTarget.getBody() == null) return null;
		
		if (mEnableLinearVelocity) {
			mTarget.getBody().setLinearVelocity(mVelocityX, mVelocityY);
		} else {
			mTarget.getBody().setAngularVelocity(mAngularVelocity);
		}
		
		return null;
	}

	@Override
	public IUpdateHandler onConditionMismatched() {
		return null;
	}

	@Override
	public ApplyVelocityResult copy(EventDrivable pNewTarget) {
		ApplyVelocityResult copy = new ApplyVelocityResult(mVelocityX, mVelocityY, mAngularVelocity, pNewTarget);
		copy.mEnableAngularVelocity = mEnableAngularVelocity;
		copy.mEnableLinearVelocity = mEnableLinearVelocity;
		
		return copy;
	}

}
